package tiled.mapeditor.util.cutter;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class BasicTileCutter implements TileCutter
{
    private int nextX, nextY;
    private BufferedImage image;
    private final int tileWidth;
    private final int tileHeight;
    private final int tileSpacing;
    private final int tileMargin;

    public BasicTileCutter(int tileWidth, int tileHeight, int tileSpacing,
            int tileMargin)
    {
        this.tileWidth = tileWidth;
        this.tileHeight = tileHeight;
        this.tileSpacing = tileSpacing;
        this.tileMargin = tileMargin;

        reset();
    }

    public String getName()
    {
        return "Basic";
    }

    public void setImage(BufferedImage image)
    {
        this.image = image;
    }

    public Image getNextTile()
    {
        if (nextY + tileHeight + tileMargin <= image.getHeight())
        {
            BufferedImage tile =
                    image.getSubimage(nextX, nextY, tileWidth, tileHeight);
            nextX += tileWidth + tileSpacing;

            if (nextX + tileWidth + tileMargin > image.getWidth())
            {
                nextX = tileMargin;
                nextY += tileHeight + tileSpacing;
            }

            return tile;
        }

        return null;
    }

    public void reset()
    {
        nextX = tileMargin;
        nextY = tileMargin;
    }

    public Dimension getTileDimensions()
    {
        return new Dimension(tileWidth, tileHeight);
    }

    public int getTileSpacing()
    {
        return tileSpacing;
    }

    public int getTileMargin()
    {
        return tileMargin;
    }

    public int getTilesPerRow()
    {
        return (image.getWidth() - 2 * tileMargin + tileSpacing) /
                (tileWidth + tileSpacing);
    }
}
